'use strict';

const router = require('koa-router')();
const fs = require('fs');

function getRouteFiles(filePath){
    let tmpPath = filePath||__dirname;
    let files = fs.readdirSync(tmpPath);
    let routeFiles = files.filter(item=>{
        return item.endsWith('.js')&&item!=='index.js'
    })
    return routeFiles;
}

function registryRoute(router,routeFiles){
    routeFiles.forEach(item=>{
        let tmpPath = __dirname+'/'+item;
        let obj = require(tmpPath);
        for(let key in obj){
            let tmpArr = key.split(' ');
            let rMethod = tmpArr[0];
            let rPath = tmpArr[1];
            let rFunction = obj[key];

            if(rMethod === 'get'){
                router.get(rPath,rFunction)
            }else if(rMethod === 'post'){
                router.post(rPath,rFunction)
            }else if(rMethod === 'put'){
                router.put(rPath,rFunction)
            }else if(rMethod === 'delete'){
                router.delete(rPath,rFunction)
            }
        }
    })
    return router.routes();
}

module.exports = function(){
    let routeFiles = getRouteFiles();
    let fn = registryRoute(router,routeFiles);
    return fn;
}